package com.wingscode.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.Query;
import com.wingscode.modules.common.entity.UserSettingEntity;
import com.wingscode.modules.common.service.UserSettingService;
import com.wingscode.modules.sys.dao.InquiryDao;
import com.wingscode.modules.sys.dao.InquiryLinkDao;
import com.wingscode.modules.sys.dao.OfferPriceDao;
import com.wingscode.modules.sys.entity.*;
import com.wingscode.modules.sys.form.InquiryQueryForm;
import com.wingscode.modules.sys.service.BuildQualService;
import com.wingscode.modules.sys.service.DictionaryValueService;
import com.wingscode.modules.sys.service.InquiryLinkService;
import com.wingscode.modules.sys.service.InquiryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


/**
 * 招标
 *
 * @author yan
 */
@Service("inquiryService")
public class InquiryServiceImpl extends ServiceImpl<InquiryDao, InquiryEntity> implements InquiryService {
	@Resource
	private BuildQualService buildQualService;
	@Resource
	private InquiryLinkService inquiryLinkService;
	@Resource
	private InquiryLinkDao inquiryLinkDao;
	@Resource
	private OfferPriceDao offerPriceDao;
	@Resource
	private DictionaryValueService dictionaryValueService;
	@Resource
	private UserSettingService userSettingService;

	@Override
	public PageUtils queryPage(InquiryQueryForm form) {
		String[] sendTypeList = null;
		String[] regionList = null;
		Map<String, Object> params = new HashMap<>();
		params.put("page", form.getPage());
		params.put("limit", form.getLimit());

		Integer userId = form.getLoginUserId() != null ? form.getLoginUserId() : null;

		// 获得当前登录用户的报价类型、区域设置
		List<UserSettingEntity> settingList = userSettingService.list(
				new QueryWrapper<UserSettingEntity>()
						.eq("user_id", userId)
		);
		if (settingList != null && settingList.size() > 0) {
			UserSettingEntity settingEntity = settingList.get(0);
			if (settingEntity.getSendType() != null && !settingEntity.getSendType().isEmpty() && settingEntity.getSendType().length() != 0)
				sendTypeList = settingEntity.getSendType().split(",");
			if (settingEntity.getAreaId() != null && !settingEntity.getAreaId().isEmpty() && settingEntity.getAreaId().length() != 0) {
				if (!settingEntity.getAreaId().contains("1"))
					regionList = settingEntity.getAreaId().split(",");
			}
		}

		IPage<InquiryEntity> page = this.baseMapper.marketList(new Query<InquiryEntity>().getPage(params), form.getClassify(), regionList, form.getType(),
				form.getIsQual(), form.getState(), form.getContent(), form.getPlatformSearch(), sendTypeList);

		if (page.getRecords() != null && page.getRecords().size() > 0) {
			for (InquiryEntity inquiry : page.getRecords()) {
//				// 获得link信息
//				List<InquiryLinkEntity> linkEntities = inquiryLinkDao.getLinkList(inquiry.getId());
//				inquiry.setLinkList(linkEntities);

				// 获得当前登陆用户是否已报价
				List<OfferPriceEntity> offerPriceEntities = offerPriceDao.getByUserId(inquiry.getId(), form.getLoginUserId());
				if (offerPriceEntities != null && offerPriceEntities.size() > 0)
					inquiry.setMineOfferPrice(true);
				else
					inquiry.setMineOfferPrice(false);
			}
		}

		return new PageUtils(page);
	}

	@Override
	@Transactional
	public void saveInquiry(InquiryEntity inquiryEntity) {
		// 保存招标信息
		inquiryEntity.setCreateTime(new Date());
		inquiryEntity.setState(0);

		this.save(inquiryEntity);

		// 保存招标link信息
		saveInquiryLink(inquiryEntity);
	}

	@Override
	@Transactional
	public void updateInquiry(InquiryEntity inquiryEntity) {
		// 更新招标信息
		inquiryEntity.setUpdateTime(new Date());
		inquiryEntity.setState(0);

		this.updateById(inquiryEntity);

		// 更新招标link信息
		// 删除原有link信息
		inquiryLinkDao.deleteByInquiry(inquiryEntity.getId());
		// 保存现有link信息
		saveInquiryLink(inquiryEntity);
	}

	private void saveInquiryLink(InquiryEntity inquiryEntity) {
		String inquiryName = "", inquiryQualType = "", buildQualName = "", newBuildQualName = "";
		// 保存现有link信息
		if (inquiryEntity.getType() == 4) {
			if (inquiryEntity.getBuildQualIdList() != null && inquiryEntity.getBuildQualIdList().size() > 0) {
				// 人才猎聘
				for (Integer id : inquiryEntity.getBuildQualIdList()) {
					InquiryLinkEntity entity = new InquiryLinkEntity();
					entity.setInquiryId(inquiryEntity.getId());
					entity.setBuildQualId(id);
					entity.setType(0);

					inquiryLinkService.save(entity);

					BuildQualEntity buildQual = buildQualService.getById(id);
					if (buildQual != null) {
						DictionaryValueEntity nameEntity = dictionaryValueService.getById(buildQual.getNameId());
						DictionaryValueEntity gradeEntity = dictionaryValueService.getById(buildQual.getGrade());
						if (nameEntity != null)
							inquiryName += nameEntity.getName() + ",";
						if (nameEntity != null && gradeEntity != null)
							buildQualName += nameEntity.getName() + gradeEntity.getName() + ",";
						DictionaryValueEntity qualTypeEntity = dictionaryValueService.getById(buildQual.getQualType());
						if (qualTypeEntity != null)
							inquiryQualType += qualTypeEntity.getName() + ",";
					}

				}
			}
		} else {
			if (inquiryEntity.getLinkList() != null && inquiryEntity.getLinkList().size() > 0) {
				// 新办设立、分立/合并、升级增项、资质整砖
				for (InquiryLinkEntity entity : inquiryEntity.getLinkList()) {
					// 根据等级获得资质信息
					if (entity.getBuildQualNameId() != null && entity.getGrade() != null) {
						BuildQualEntity buildQual = buildQualService.getByGrade(entity.getBuildQualNameId(), entity.getGrade());
						if (buildQual != null) {
							entity.setInquiryId(inquiryEntity.getId());
							entity.setBuildQualId(buildQual.getId());
							entity.setType(0);

							inquiryLinkService.save(entity);

							DictionaryValueEntity nameEntity = dictionaryValueService.getById(buildQual.getNameId());
							DictionaryValueEntity gradeEntity = dictionaryValueService.getById(buildQual.getGrade());
							if (nameEntity != null)
								inquiryName += nameEntity.getName() + ",";
							if (nameEntity != null && gradeEntity != null)
								buildQualName += nameEntity.getName() + gradeEntity.getName() + ",";
							DictionaryValueEntity qualTypeEntity = dictionaryValueService.getById(buildQual.getQualType());
							if (qualTypeEntity != null)
								inquiryQualType += qualTypeEntity.getName() + ",";
						}
					}
				}
			}

			// 保存升级增项后的招标link
			if (inquiryEntity.getType() == 3) {
				if (inquiryEntity.getNewLinkList() != null && inquiryEntity.getNewLinkList().size() > 0) {
					for (InquiryLinkEntity newEntity : inquiryEntity.getNewLinkList()) {
						// 根据等级获得资质信息
						if (newEntity.getBuildQualNameId() != null && newEntity.getGrade() != null) {
							BuildQualEntity buildQual = buildQualService.getByGrade(newEntity.getBuildQualNameId(), newEntity.getGrade());
							if (buildQual != null) {
								newEntity.setInquiryId(inquiryEntity.getId());
								newEntity.setBuildQualId(buildQual.getId());
								newEntity.setType(1);

								inquiryLinkService.save(newEntity);

								DictionaryValueEntity nameEntity = dictionaryValueService.getById(buildQual.getNameId());
								DictionaryValueEntity gradeEntity = dictionaryValueService.getById(buildQual.getGrade());
								if (nameEntity != null)
									inquiryName += nameEntity.getName() + ",";
								if (nameEntity != null && gradeEntity != null)
									newBuildQualName += nameEntity.getName() + gradeEntity.getName() + ",";
								DictionaryValueEntity qualTypeEntity = dictionaryValueService.getById(buildQual.getQualType());
								if (qualTypeEntity != null)
									inquiryQualType += qualTypeEntity.getName() + ",";
							}
						}
					}
				}
			}
		}

		if (!inquiryName.isEmpty())
			inquiryName = inquiryName.substring(0, inquiryName.length() - 1);
		if (!inquiryQualType.isEmpty())
			inquiryQualType = inquiryQualType.substring(0, inquiryQualType.length() - 1);
		if (!buildQualName.isEmpty())
			buildQualName = buildQualName.substring(0, buildQualName.length() - 1);
		if (!newBuildQualName.isEmpty())
			newBuildQualName = newBuildQualName.substring(0, newBuildQualName.length() - 1);

		inquiryEntity.setInquiryName(inquiryName);
		inquiryEntity.setInquiryQualType(inquiryQualType);
		if (inquiryEntity.getType() == 3) {
			inquiryEntity.setBuildQualName(newBuildQualName);
			inquiryEntity.setOldBuildQualName(buildQualName);
		} else {
			inquiryEntity.setBuildQualName(buildQualName);
		}
		this.updateById(inquiryEntity);
	}

	@Override
	public void deleteBatch(Long[] ids) {
		this.removeByIds(Arrays.asList(ids));
	}

	@Override
	public InquiryEntity getInfo(Integer id) { return this.baseMapper.getInfo(id); }

	@Override
	public PageUtils mainList(InquiryQueryForm form) {
		String[] regionList = null;
		Map<String, Object> params = new HashMap<>();
		params.put("page", form.getPage());
		params.put("limit", form.getLimit());

		Integer userId = form.getLoginUserId() != null ? form.getLoginUserId() : null;

		// 获得当前登录用户的报价类型、区域设置
		List<UserSettingEntity> settingList = userSettingService.list(
				new QueryWrapper<UserSettingEntity>()
						.eq("user_id", userId)
		);
		if (settingList != null && settingList.size() > 0) {
			UserSettingEntity settingEntity = settingList.get(0);
			if (settingEntity.getAreaId() != null && !settingEntity.getAreaId().isEmpty() && settingEntity.getAreaId().length() != 0) {
				if (!settingEntity.getAreaId().contains("1"))
					regionList = settingEntity.getAreaId().split(",");
			}
		}

		IPage<InquiryEntity> page = this.baseMapper.mainList(new Query<InquiryEntity>().getPage(params), regionList, form.getType(), form.getIsQual(),
				form.getStartTime(), form.getEndTime(), form.getPrice(), form.getContent());

//		if (page.getRecords() != null && page.getRecords().size() > 0) {
//			for (InquiryEntity inquiry : page.getRecords()) {
//				// 获得link信息
//				List<InquiryLinkEntity> linkEntities = inquiryLinkDao.getLinkList(inquiry.getId());
//				inquiry.setLinkList(linkEntities);
//			}
//		}

		return new PageUtils(page);
	}

	@Override
	public PageUtils myList(InquiryQueryForm form) {
		Map<String, Object> params = new HashMap<>();
		params.put("page", form.getPage());
		params.put("limit", form.getLimit());

		IPage<InquiryEntity> page = this.baseMapper.myList(new Query<InquiryEntity>().getPage(params), form.getLoginUserId(), form.getAgentId(),
				form.getState(), form.getClassify());

		if (page.getRecords() != null && page.getRecords().size() > 0) {
			for (InquiryEntity inquiry : page.getRecords()) {
				// 获得link信息
				List<InquiryLinkEntity> linkEntities = inquiryLinkDao.getLinkList(inquiry.getId());
				inquiry.setLinkList(linkEntities);

				List<OfferPriceEntity> offerPriceEntities = offerPriceDao.getListByInquiryId(inquiry.getId());
				inquiry.setOfferPriceList(offerPriceEntities);
			}
		}

		return new PageUtils(page);
	}

	@Override
	public PageUtils myOfferPriceList(InquiryQueryForm form) {
		Map<String, Object> params = new HashMap<>();
		params.put("page", form.getPage());
		params.put("limit", form.getLimit());

		IPage<InquiryEntity> page = this.baseMapper.myOfferPriceList(new Query<InquiryEntity>().getPage(params), form.getLoginUserId(), form.getState());

		if (page.getRecords() != null && page.getRecords().size() > 0) {
			for (InquiryEntity inquiry : page.getRecords()) {
				// 获得link信息
				List<InquiryLinkEntity> linkEntities = inquiryLinkDao.getLinkList(inquiry.getId());
				inquiry.setLinkList(linkEntities);
			}
		}

		return new PageUtils(page);
	}

	@Override
	public PageUtils queryMarketPage(Map<String, Object> params) {
		Integer type = null, state = null, classify = null;
		String username = "";
		if (params.containsKey("type") && params.get("type") != null)
			type = Integer.parseInt(params.get("type").toString());
		if (params.containsKey("state") && params.get("state") != null)
			state = Integer.parseInt(params.get("state").toString());
		if (params.containsKey("classify") && params.get("classify") != null)
			classify = Integer.parseInt(params.get("classify").toString());
		if (params.containsKey("username"))
			username = (String) params.get("username");

		IPage<InquiryEntity> page = this.baseMapper.list(new Query<InquiryEntity>().getPage(params), type, state, classify, username);

		return new PageUtils(page);
	}

	@Override
	public List<InquiryEntity> invalidList() { return this.baseMapper.invalidList(); }
}
